<?php

namespace App\Http\Controllers\Util;

use App\Exceptions\ValidException;
use App\Notifications\RegisterNotify;
use App\User;
use Houdunwang\Aliyun\Aliyun;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CodeController extends Controller
{
    protected $expire;
    public function __construct()
    {
        $this->expire = hd_config('base.code_expire');
    }


    public function send(Request $request){
        $this->expireCheck();
        $code=hd_random();
        if(filter_var($request->username,FILTER_VALIDATE_EMAIL)){
            $type='email';
            $user =User::firstOrNew ( [ 'email' => $request->username ] );
            $user->notify ( new RegisterNotify( $code ) );


        }elseif(preg_match('/^\d{11}$/',$request->username)){
            $type='moblie';

            $data = [
                //短信签名
                'sign'     => '个人技术分享',
                //短信模板
                'template' => 'SMS_144146118',
                //手机号
                'mobile'   => $request->username,
                //模板变量
                'vars'     => ["code" => $code],
            ];
            //发送手机验证码
//            $res = Aliyun::instance('Sms')->send($data);
        }else{
            return ['code' => 0, 'message' => '请输入正确的邮箱或者手机号'];
        }
        $this->saveToSession ($code,$type,$request->username);
        return ['code'=>1,'message'=>'验证码发送成功'];
    }
    public function saveToSession($code,$type,$username){
        session ()->put ( 'validate_code' , [
            'code'     => $code ,
            'type'     => $type ,
            'username' => $username ,
            'expire'   => time () + $this->expire
        ] );
    }

    public function expireCheck ()
    {
        //获得session中存储的过期时间
        $expire = session ( 'validate_code.expire' );
        //过期时间存在并且小于当前时间，说明验证码未过期
        if ( $expire && time () < $expire ) {
            throw  new ValidException( '验证码发送频繁,请稍后操作' );
        }
    }
}
